<template>
  <div class="major" style="margin-top: 30px">
    <div class="major-left">院校省份</div>
    <div class="major-right">
      <div
        class="major-size"
        v-for="(item, idx) in provincelist"
        :key="idx"
        :class="{ active: provinceIndexs.includes(idx) }"
        @click="handleSchoolSelection('province', idx, item)"
      >
        {{ item }}
      </div>
    </div>
  </div>
  <div class="major">
    <div class="major-left">院校类型</div>
    <div class="major-right">
      <div
        class="major-size"
        v-for="(item, index) in schoolType"
        :key="index"
        :class="{ active: typeIndexs.includes(index) }"
        @click="handleSchoolSelection('type', index, item)"
      >
        {{ item }}
      </div>
    </div>
  </div>
  <div class="major">
    <div class="major-left">院校层次</div>
    <div class="major-right alitem">
      <div
        class="major-size"
        v-for="(item, ids) in studentType"
        :key="ids"
        :class="{ active: featureIndexs.includes(ids) }"
        @click="handleSchoolSelection('school_feature', ids, item)"
      >
        {{ item }}
      </div>
    </div>
  </div>
  <div class="major">
    <div class="major-left">院校性质</div>
    <div class="major-right alitem">
      <div
        class="major-size"
        v-for="(item, index) in natureTypelist"
        :key="index"
        :class="{ active: natureTypeIndex.includes(index) }"
        @click="handleSchoolSelection('nature', index, item)"
      >
        {{ item }}
      </div>
      <!-- <el-divider direction="vertical" /> -->
      <div
        class="major-size"
        v-for="(item, index) in fTypelist"
        :key="index"
        :class="{ active: schoolTypeIndexs.includes(index) }"
        @click="handleSchoolSelection('school_type', index, item)"
      >
        {{ item }}
      </div>
      <!-- <el-divider direction="vertical" /> -->
      <div
        class="major-size"
        v-for="(item, index) in schoolNewlylist"
        :key="index"
        :class="{ active: schoolNewlyIndexs.includes(index) }"
        @click="handleSchoolSelection('schoolNewly', index, item)"
      >
        {{ item }}
      </div>
    </div>
  </div>
  <el-row class="matop">
    <el-col :span="12">
      <div class="alitem">
        <div class="major-left">意向院校</div>
        <el-input
          ref="buttonRef"
          v-model="searchKey"
          style="width: 240px"
          placeholder="输入意向院校"
          clearable
          @input="searchKeyInput"
          @focus="isShowSearchPop = true"
          @blur="isShowSearchPop = false"
        >
          <template #prefix>
            <el-icon class="el-input__icon">
              <search />
            </el-icon>
          </template>
        </el-input>
        <div style="margin: 0 6px 0 20px">
          <el-checkbox
            v-model="isAllchecked"
            :label="`用户关注(${schoolData.length})`"
            size="large"
            @change="toggleAll"
          />
        </div>
        <div style="margin-top: 4px">
          <el-popover
            :visible="visible"
            ref="myPopover"
            placement="bottom"
            :width="180"
            v-model:visible="showPopover"
          >
            <span v-if="schoolData.length == 0">暂无关注的意向院校...</span>
            <div
              style="display: flex; flex-direction: column"
              v-for="(item, index) in schoolData"
              :key="index"
            >
              <el-checkbox-group v-model="Cities.checkedCities">
                <el-checkbox
                  @change="changeItem"
                  :value="item"
                  :label="item.cnName"
                  size="large"
                />
              </el-checkbox-group>
            </div>

            <div
              style="display: flex; justify-content: flex-end"
              v-if="schoolData.length != 0"
            >
              <el-button type="primary" size="small" @mousedown="schoolSubmit"
                >确定</el-button
              >
            </div>

            <template #reference>
              <el-icon
                @click="visible = !visible"
                class="el-icon--right"
                size="16"
              >
                <ArrowDown />
              </el-icon>
            </template>
          </el-popover>
        </div>
        <div
          v-show="isShowSearchPop && searchList.length > 0"
          class="search-popover"
        >
          <div
            v-for="(item, index) in searchList"
            :key="index"
            @mousedown="onClickSearchItem(item, index)"
          >
            <div style="padding: 5px 0">
              {{ index == 0 ? '在筛选条件中搜索 "' + item + '"' : item.cnName }}
            </div>
            <div
              v-if="index + 1 < searchList.length"
              style="width: 100%; height: 1px; background-color: #eee"
            ></div>
          </div>
        </div>
      </div>
    </el-col>
  </el-row>
</template>
<script setup>
import { ref, onMounted, reactive } from 'vue';
import { searchSchool, searchSchoolFilter } from '@/api/volunteer/volunteer.js';
import { useStore } from 'vuex';
import _ from 'lodash';
const store = useStore();

const searchList = ref([]); // 模糊搜索数据源
// 筛选数据
const studentType = ref([]); // 院校层次
const provincelist = ref([]); // 省份
const schoolType = ref([]); // 学校类型
const natureTypelist = ref([]); // 学校类型
const fTypelist = ref({}); // 学校类型
const schoolNewlylist = ref([]); // 学校类型

// 选中的筛选下标数据
const provinceIndexs = ref(['0']); // 院校省份 '0' 全国
const typeIndexs = ref([0]); // 院校类型 0 不限
const featureIndexs = ref([0]); // 院校层次 0 不限
const natureTypeIndex = ref([]); // 院校性质 公办、民办、中外/港澳
const schoolTypeIndexs = ref([]); // 院校性质 本科、专科
const schoolNewlyIndexs = ref([]); // 院校性质 新增、非新增

// 所有已选筛选条件 格式 [...,{type:'类型', code:'id', name:'标题'},...]
const selItemArray = ref([]);
const searchKey = ref(''); // 搜索关键词
const isShowSearchPop = ref(false); // 是否显示搜索pop
const isAllchecked = ref(false);
// const schoolDetail = ref(0);
const visible = ref(false);
const schoolList = ref([]);
const showPopover = ref(false);
const Cities = reactive({
  checkedCities: [],
});
// const like = ref({
//   type: '',
//   detail: '1',
// });
const { schoolData } = defineProps({
  // 批次线信息
  schoolData: {
    type: Array,
    default: () => [],
  },
});
/**
 * 删除某条筛选条件
 * @param {Object} item {type:'类型', code:'id', name:'标题'}
 */
function deleteScreenItem(item) {
  handleSchoolSelection(item.type, item.code, item.name);
}
function closeV() {
  visible.value = false;
}
function deleteAll() {
  provinceIndexs.value = ['0'];
  typeIndexs.value = [0];
  featureIndexs.value = [0];
  natureTypeIndex.value = [];
  schoolTypeIndexs.value = [];
  schoolNewlyIndexs.value = [];

  selItemArray.value = [];
  // userSearchVal.saveSchoolInfoChange([]); // 保存到 store 中
  store.dispatch('tianbao/saveSchoolInfoChange', []);
}

/**
 * @param {Object} type province-院校省份 type-院校类型 school_feature-院校层次 nature-院校性质>办学类型 school_type-院校性质>办学层次 schoolNewly-院校性质>更多筛选
 * @param {Number} code 筛选ID
 * @param {Object} name 筛选标题
 */
function handleSchoolSelection(type, code, name) {
  if (store.getters.user.userInfo.isVIP != 0) {
    const selectedItem = {
      code: code,
      name: name,
      type: type,
    };
    if (type === 'schoolNewly') {
      // 院校性质  新增、非新增
      if (schoolNewlyIndexs.value.includes(code)) {
        schoolNewlyIndexs.value = schoolNewlyIndexs.value.filter(
          (i) => i !== code,
        );
        selItemArray.value = selItemArray.value.filter(
          (obj) => obj.code !== code || obj.type !== 'schoolNewly',
        );
      } else {
        schoolNewlyIndexs.value.push(code);
        selItemArray.value.push(selectedItem);
      }
    }
    if (type === 'school_type') {
      // 院校性质  本科、专科
      if (schoolTypeIndexs.value.includes(code)) {
        schoolTypeIndexs.value = schoolTypeIndexs.value.filter(
          (i) => i !== code,
        );
        selItemArray.value = selItemArray.value.filter(
          (obj) => obj.code !== code || obj.type !== 'school_type',
        );
      } else {
        schoolTypeIndexs.value.push(code);
        selItemArray.value.push(selectedItem);
      }
    }
    if (type === 'nature') {
      // 院校性质 公办、民办、中外/港澳
      if (natureTypeIndex.value.includes(code)) {
        natureTypeIndex.value = natureTypeIndex.value.filter((i) => i !== code);
        selItemArray.value = selItemArray.value.filter(
          (obj) => obj.code !== code || obj.type !== 'nature',
        );
      } else {
        natureTypeIndex.value.push(code);
        selItemArray.value.push(selectedItem);
      }
    }
    if (type === 'school_feature') {
      // 院校层次
      if (code === 0) {
        featureIndexs.value = [0];
        // levelArray.value = [];
        selItemArray.value = selItemArray.value.filter(
          (i) => i.type !== 'school_feature',
        );
      } else {
        if (featureIndexs.value.includes(code)) {
          featureIndexs.value = featureIndexs.value.filter((i) => i !== code);
          selItemArray.value = selItemArray.value.filter(
            (obj) => obj.code !== code || obj.type != type,
          );

          if (featureIndexs.value.length == 0) {
            featureIndexs.value = [0];
          }
        } else {
          if (featureIndexs.value.includes(0)) {
            featureIndexs.value = featureIndexs.value.filter((i) => i !== 0);
            selItemArray.value = selItemArray.value.filter(
              (obj) => obj.code !== 0 || obj.type !== 'school_feature',
            );
          }
          featureIndexs.value.push(code);
          selItemArray.value.push(selectedItem);
        }
      }
    } else if (type === 'type') {
      // 院校类型
      if (code === 0) {
        typeIndexs.value = [0];
        // typeArray.value = [];
        selItemArray.value = selItemArray.value.filter(
          (i) => i.type !== 'type',
        );
      } else {
        if (typeIndexs.value.includes(code)) {
          typeIndexs.value = typeIndexs.value.filter((i) => i !== code);
          selItemArray.value = selItemArray.value.filter(
            (obj) => obj.code !== code || obj.type != type,
          );

          if (typeIndexs.value.length == 0) {
            typeIndexs.value = [0];
          }
        } else {
          if (typeIndexs.value.includes(0)) {
            typeIndexs.value = typeIndexs.value.filter((i) => i !== 0);
            selItemArray.value = selItemArray.value.filter(
              (obj) => obj.code !== 0 || obj.type !== 'type',
            );
          }
          typeIndexs.value.push(code);
          selItemArray.value.push(selectedItem);
        }
      }
    } else if (type === 'province') {
      // 院校省份
      if (code === '0') {
        provinceIndexs.value = ['0'];
        // provinceArray.value = [];
        selItemArray.value = selItemArray.value.filter(
          (i) => i.type !== 'province',
        );
      } else {
        if (provinceIndexs.value.includes(code)) {
          provinceIndexs.value = provinceIndexs.value.filter((i) => i !== code);
          selItemArray.value = selItemArray.value.filter(
            (obj) => obj.code !== code || obj.type != type,
          );

          if (provinceIndexs.value.length == 0) {
            provinceIndexs.value = ['0'];
          }
        } else {
          if (provinceIndexs.value.includes('0')) {
            provinceIndexs.value = provinceIndexs.value.filter(
              (i) => i !== '0',
            );
            selItemArray.value = selItemArray.value.filter(
              (obj) => obj.code !== '0' || obj.type !== 'province',
            );
          }
          provinceIndexs.value.push(code);
          selItemArray.value.push(selectedItem);
        }
      }
    } else if (type == 'schoolSearch') {
      // 这里只处理删除逻辑 添加逻辑在 onClickSearchItem 函数中
      selItemArray.value = selItemArray.value.filter(
        (i) => i.code !== code || i.type !== 'schoolSearch',
      );
    } else if (type == 'ssearch') {
      // 这里只处理删除逻辑 添加逻辑在 onClickSearchItem 函数中
      selItemArray.value = selItemArray.value.filter(
        (i) => i.type !== 'ssearch',
      );
    }

    saveSchoolInfoChange(selItemArray.value);
  } else {
    return;
  }
}
// getLikeList();
const toggleAll = (val) => {
  if (val) {
    // 全选操作
    if (schoolData.length) {
      schoolData.forEach((v) => {
        v.isChange = true; // 标记为已选
        if (!Cities.checkedCities.includes(v.code)) {
          Cities.checkedCities.push(v);
        }
      });
    }

    // 将选中的项存储到 selItemArray
    if (Cities.checkedCities.length > 0) {
      Cities.checkedCities.forEach((itemCode) => {
        const selectedItem = schoolData.find(
          (item) => item.code === itemCode.code,
        );
        if (selectedItem) {
          const selectedItemObject = {
            code: selectedItem.code,
            name: selectedItem.cnName,
            type: 'schoolSearch',
          };
          let index = selItemArray.value.findIndex(
            (i) => i.code == selectedItem.code,
          );
          if (index < 0) {
            selItemArray.value.push(selectedItemObject);
            store.dispatch('tianbao/saveSchoolInfoChange', selItemArray.value);
          }
        }
      });
    }
  } else {
    // 取消全选操作
    schoolData.forEach((v) => {
      v.isChange = false; // 标记为未选
      const index = Cities.checkedCities.indexOf(v);
      if (index !== -1) {
        Cities.checkedCities.splice(index, 1); // 移除已选项
      }
    });

    // 如果取消全选，清空 selItemArray
    selItemArray.value = [];
    store.dispatch('tianbao/saveSchoolInfoChange', selItemArray.value);
  }
  visible.value = false;
};
const changeItem = () => {
  isAllchecked.value = Cities.checkedCities.length === schoolList.value.length;
};
const saveSchoolInfoChange = _.throttle((val) => {
  store.dispatch('tianbao/saveSchoolInfoChange', val);
}, 800);
// 搜索输入值改变
const searchKeyInput = _.throttle((val) => {
  if (val.length >= 2) {
    searchSchool({
      search: val,
      pageSize: 1000,
    }).then((res) => {
      // console.log('--res--', res)
      let data = res.data.data;
      searchList.value = data;

      searchList.value.splice(0, 0, searchKey.value);
      isShowSearchPop.value = true;
    });
  } else {
    searchList.value = [];
    isShowSearchPop.value = false;
  }
}, 800);

//学校筛选
const schoolSubmit = () => {
  if (Cities.checkedCities.length !== schoolList.value.length) {
    isAllchecked.value = false;
  }
  if (Cities.checkedCities.length > 0) {
    Cities.checkedCities.forEach((item) => {
      const selectedItem = {
        code: item.code,
        name: item.cnName,
        type: 'schoolSearch',
      };
      let index = selItemArray.value.findIndex((i) => i.code == item.code);
      if (index < 0) {
        selItemArray.value.push(selectedItem);
        store.dispatch('tianbao/saveSchoolInfoChange', selItemArray.value);
      }
    });
  }
  visible.value = false;
};
function onClickSearchItem(item, index) {
  if (index == 0) {
    // 模糊搜索
    const selectedItem = {
      code: 0,
      name: item,
      type: 'ssearch',
    };

    selItemArray.value = selItemArray.value.filter(
      (obj) => obj.type !== 'ssearch',
    );
    selItemArray.value.push(selectedItem);
    store.dispatch('tianbao/saveSchoolInfoChange', selItemArray.value);
  } else {
    // 精准学校code搜索
    const selectedItem = {
      code: item.code,
      name: item.cnName,
      type: 'schoolSearch',
    };

    let index = selItemArray.value.findIndex((i) => i.code == item.code);
    if (index < 0) {
      selItemArray.value.push(selectedItem);
      store.dispatch('tianbao/saveSchoolInfoChange', selItemArray.value);
    }
  }

  // 添加后清除搜索数据
  searchKey.value = '';
  searchList.value = [];
  isShowSearchPop.value = false;
}

/**
 * 获取院校筛选数据
 */
function getSearchDate() {
  searchSchoolFilter({}).then((res) => {
    let data = res.data.data;
    provincelist.value = data.province; // 省份
    schoolType.value = data.categories; // 院校类型
    studentType.value = [...data.features];
    natureTypelist.value = data.natureType;
    fTypelist.value = data.eduLevel;
    schoolNewlylist.value = data.schoolNewly;

    if (Number(localStorage.getItem('isYJTB')) == 1) {
      let selArr = JSON.parse(localStorage.getItem('schoolArrayList')) || [];
      selArr.forEach((item) => {
        deleteScreenItem(item);
      });
    }
  });
}

onMounted(() => {
  getSearchDate();
});

defineExpose({
  deleteScreenItem,
  deleteAll,
  closeV,
});
</script>
<style lang="scss" scoped>
.flexend {
  div {
    font-size: 14px;
    font-weight: 400;
    color: #4e5969;
    line-height: 14px;
    margin-right: 20px;
  }
}
.major-left {
  width: 100px;
  font-size: 14px;
  text-align: center;
  color: #9b9b9b;
}
.major {
  display: flex;
  margin-top: 10px;

  .major-right {
    flex: 1;
    display: flex;
    flex-wrap: wrap;
    align-items: center;

    .major-size {
      font-size: 14px;
      margin-bottom: 12px;
      padding: 4px 16px;
      margin-right: 10px;
      text-align: center;
      border: 1px solid #e5e6eb;
      border-radius: 4px;
      cursor: pointer;
      color: #4e5969;
    }

    .active {
      border: 1px solid #004cf7;
      color: #004cf7;
    }
  }
}

.search-popover {
  position: absolute;
  top: 40px;
  left: 15px;
  width: 240px;
  height: 200px;
  overflow: auto;
  background-color: white;
  z-index: 999;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border-radius: 4px;
  border: 1px solid #c9cdd4;
  padding: 0 10px;
  font-size: 14px;
}
</style>
